package com.service.impl;

import com.entity.Role;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.RoleMapper;
import com.service.IRoleService;
import com.until.ConstantUtil;
import com.vo.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Resource
    private RoleMapper roleMapper;

    @Override
    public List<Role> listAll() {
        Role role = new Role();
        role.setRoleStatus(ConstantUtil.RoleStatus.ENABLED);
        return roleMapper.listByParam(role);
    }

    @Override
    public PageInfo<Role> listByParam(Page<Role> page) {
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        return new PageInfo<Role>(roleMapper.listByParam(page.getData()));
    }

    @Override
    public Role getByRoleId(Integer roleId) {
        return roleMapper.getByRoleId(roleId);
    }

    @Override
    public int insert(Role role) {
        return roleMapper.insert(role);
    }

    @Override
    public int delete(Integer roleId) {
        return roleMapper.delete(roleId);
    }

    @Override
    public int update(Role role) {
        return roleMapper.update(role);
    }


    //查询角色权限关联表  根据角色ID查询该角色关联的所有权限ID集合
    @Override
    public List<Integer> listMenuIdByRoleId(Integer roleId) {
        return roleMapper.listMenuIdByRoleId(roleId);
    }


    @Override
    public int deleteMenuByRoleId(Integer roleId) {
        return roleMapper.deleteMenuByRoleId(roleId);
    }

    @Transactional
    @Override
    public int insertRoleAndMenu(Integer roleId, String ids) {
        //1,先调用根据角色批量删除 角色权限关联的方法
        this.deleteMenuByRoleId(roleId);
        //2,再添加关联
        //posId = 1   每次一个值 角色/职位编号
        //menuIds = "100,101,102,200,201,300"
        //添加是否成功标识符
        boolean flag=true;
        //判断menuIds是否为空 不为空时，分割，添加
        if(!StringUtils.isEmpty(ids)){
            String[] idArray=ids.split(",");
            for(String id:idArray){
                int i = roleMapper.insertRoleAndMenu(roleId, Integer.valueOf(id));
                if(i<1){
                    flag=false;
                }
            }
        }
        if(flag){
            //如果循环添加结束，flag仍然是true说明 全部成功
            return 0;
        }
        return 1;
    }
}
